package com.assisjrs.jpaandroid.persistence.converter;

import java.lang.reflect.Field;

import android.database.Cursor;

import com.assisjrs.jpaandroid.persistence.ConverterDatabase;
import com.assisjrs.jpaandroid.persistence.Entity;

public class EnumConverter implements ConverterDatabase<Enum<?>, Short> {
	@Override
	public Short getFromInstance(final Field field, final Entity entity) {
		try {
			final Enum<?> value = (Enum<?>) field.get(entity);

			if (value == null)
				return null;

			return Integer.valueOf(value.ordinal()).shortValue();
		} catch (final IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (final IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Enum<?> getToInstance(final Cursor cursor, final int columnIndex, final Class<?> type) {
		final Short valorEmShort = cursor.getShort(columnIndex);
		final Enum<?>[] enumConstants = (Enum[]) type.getEnumConstants();

		if (valorEmShort < 0 || valorEmShort > enumConstants.length)
			throw new IllegalStateException("Valor do dado em enum maior ou menor que o permitido.");

		return enumConstants[valorEmShort];
	}
}
